#!/bin/bash


APP_STARTING_TIMES=${APP_STARTING_TIMES}
[ ! $APP_STARTING_TIMES ] && APP_STARTING_TIMES=300

DEBUG_APP=${DEBUG_APP}
[ ! $DEBUG_APP ] && DEBUG_APP="false"

if [ "$APP_DEF"x = x ]
then
    APP_DEF=./docker-app.def
fi

source ${APP_DEF}

waiting_until_running() {
    print_log "Waiting until service running"
    sleep $APP_STARTING_TIMES
}

watch_loop() {
    LOOP_SECS=5
    RETRY_SEC=3
    MAX_ERR=5
    ERR_CNT=0
    sleep 10
    while [ true ]
    do
        RET_CODE=0
        readiness
        RET_CODE=$[$RET_CODE | 0 ]
        if [ ${RET_CODE} == 0 ]
        then
           ERR_CNT=0
           sleep $LOOP_SECS
        else
            ERR_CNT=$[$ERR_CNT+1]
            print_log "Readiness probe failed, retry $ERR_CNT"
            if [ $ERR_CNT -ge $MAX_ERR ]
            then
                print_log "Readiness probe failed 5 times, container quit"
                break;
            fi
           sleep $RETRY_SEC
         fi
    done
}

print_log(){
    print_console "WARN" "$1"
}

print_console()
{
    printf "[$(date +'%Y-%m-%d %H:%M:%S')][$1]->[%s]\n" "$2"
 }

print_debug(){
    if [ ${DEBUG} ]
    then
        print_console "DEBUG" "$1"
    fi
}

running_forever() {
    while :; do
        sleep 300
    done
}

readiness() {
    RET_CODE=0
    for APPNODE in ${APP[@]}
    do
        eval VERIFY_SCRIPT=\${${APPNODE}[4]}
        eval VERIFY_NORMAL=\${${APPNODE}[5]}
        if [ ! "$VERIFY_SCRIPT"x = x -a ! "$VERIFY_NORMAL"x = x ]
        then
            resp_code=$(eval $VERIFY_SCRIPT)
            print_debug "readiness app: [$APPNODE] response_code:[$resp_code]"
            if [ "$resp_code"x = "$VERIFY_NORMAL"x ]
            then
                RET_CODE=$[$RET_CODE | 0 ]
            else
                print_log "Verify script: $VERIFY_SCRIPT, expect response result: $VERIFY_NORMAL, current response result: $resp_code"
                RET_CODE=$[$RET_CODE | 1 ]
            fi
            if [[ ${DEBUG_APP} == "true" ]]
            then
                print_log "DEBUG APP"
                RET_CODE=0
            fi
            if [ ${RET_CODE} != 0 ]
            then
                return $RET_CODE
            fi
        fi
    done
    return $RET_CODE
}

if [ $KUBERNETES_SERVICE_HOST ]; then
	running_forever
else
	waiting_until_running
    watch_loop
fi